<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\WxMinigameConfig;
use App\Services\WxMinigameMessageService;
use Illuminate\Http\Request;

class WxMinigameMessageController extends Controller
{
    private function returnMsgOkToWechat()
    {
        return 'success';
    }

    // 微信客服消息推送，由微信异步回调过来
    // https://developers.weixin.qq.com/minigame/dev/guide/open-ability/message-push.html
    public function message($appid, Request $request)
    {
        $params = $request->input();

        $mini = WxMinigameConfig::where('appid', $appid)->first();
        if (empty($mini)) {
            return $this->returnMsgOkToWechat();
        }

        // 验证签名
        if (!WxMinigameMessageService::getInstance()->checkMsgSign($params, $mini->message_token)) {
            return $this->returnMsgOkToWechat();
        }

        // 如果收到echostr，表示微信发来做接口验证的，按文档要求直接原样返回
        if (isset($params['echostr'])) {
            return $params['echostr'];
        }

        // 处理消息
        WxMinigameMessageService::getInstance()->handleMsg($mini, $params);

        return $this->returnMsgOkToWechat();
    }
}
